﻿using HttpArchive;
using ImgToTxt;
using JsonArchive;
using ResourceDllLoader;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using UpdateHelper;
using Excel = Microsoft.Office.Interop.Excel;
using Html = HtmlAgilityPack;

namespace EnterpriseSearchPlatform
{
    public partial class SearchPlatform : Form
    {
        public SearchPlatform()
        {
            InitializeComponent();
            LoadResourceDll.RegistDLL();
        }
        private void SearchPlatform_Load(object sender, EventArgs e)
        {
            UpdateCheck.Start();
        }

        static String labelInfoText = null;
        List<string> EnterpriseNameList = new List<string>();
        
        /// <summary>
        /// 获取小微企业名录
        /// </summary>
        /// <returns></returns>
        public static List<string> GetComNameList()
        {
            String postURL = "http://120.26.117.210:8080/fzw/index.php/Home/FirstVersion/IndexService/dispatchIndexService";
            String postData = "{\"target\":\"sunshineDataManage\",\"req_method\":\"other\",\"action\":\"get\",\"sid\":\"\",\"fields\":{\"module\":\"judgeShow\",\"pageNum\":1,\"pageSize\":1000}}";
            String webtext = Http.POST(postURL, postData, Encoding.UTF8);
            webtext = Http.UnicodeToGB(webtext);
            Dictionary<string, object> JSON = J2D.JsonToDictionary(webtext);
            Dictionary<string, object> data = (Dictionary<string, object>)JSON["data"];
            ArrayList LibArray = (ArrayList)data["rows"];
            List<string> ComNameList = new List<string>();
            foreach (var Lib in LibArray)
            {
                Dictionary<string, object> Item = (Dictionary<string, object>)Lib;
                ComNameList.Add(Item["firm_name"].ToString());
            }
            return ComNameList;
        }
        /// <summary>
        /// 识别验证码
        /// </summary>
        /// <returns></returns>
        public static string getCode()
        {
            int num1 = 100, num2 = 100;
            int equation = 0;
            Image img = null;

            while (img == null)
            {
                img = Http.GetImg("http://gsxt.cqgs.gov.cn/sc.action?width=130&height=40&fs=23");
            }
            string[] CaptchaString = Captcha.BmpToStringH(new Bitmap(img));

            for (int i = 0; i < 10; i++)
            {
                if (CaptchaString[5].Contains(Captcha.CodeNum[i][4]))
                {
                    num1 = i;
                }
            }
            for (int i = 0; i < 10; i++)
            {
                if (CaptchaString[48].Contains(Captcha.CodeNum[i][4]))
                {
                    num2 = i;
                }
            }
            if (CaptchaString[36].Contains(Captcha.CodeNum[10][2]))
            {
                equation = num1 + num2;
            }
            else
            {
                equation = num1 - num2;
            }

            if (num1 == 100 || num2 == 100)
            {
                return null;
            }
            return equation.ToString();
        }
        /// <summary>
        /// 获取企业信息
        /// </summary>
        /// <param name="EnterpriseName">企业名称</param>
        /// <returns>企业信息</returns>
        public static string[] GetEnterpriseInfo(string EnterpriseName)
        {
            string[] EnterpriseInfo = new string[11];

            String CodeNum = null;
            while (CodeNum == null)
            {
                CodeNum = getCode();
            }
            String postdata = string.Format("stype=&outSearch=&key={0}&code={1}", EnterpriseName, CodeNum);
            String pagedata = null;
            while (pagedata == null)
            {
                pagedata = Http.POST("http://gsxt.cqgs.gov.cn/search.action", postdata, Encoding.UTF8);
            }

            Html.HtmlDocument doc = new Html.HtmlDocument();
            Html.HtmlNode pagenode = null;

            doc.LoadHtml(pagedata);
            pagenode = doc.DocumentNode.SelectSingleNode("//*[@id='wrap']/div[1]");
            if (pagenode.HasAttributes)
            {
                EnterpriseInfo[0] = EnterpriseName;
                EnterpriseInfo[1] = "Error";
                EnterpriseInfo[2] = pagenode.InnerText.Trim();
                return EnterpriseInfo;
            }
            if (pagedata.Contains("您搜索的条件无查询结果"))
            {
                EnterpriseInfo[0] = EnterpriseName;
                EnterpriseInfo[1] = "Error";
                EnterpriseInfo[2] = "您搜索的条件无查询结果";
                return EnterpriseInfo;
            }

            pagenode = doc.DocumentNode.SelectSingleNode("//*[@id='result']/div[1]/a");
            string dataid = pagenode.Attributes["data-id"].Value;
            string type = pagenode.Attributes["data-type"].Value;
            string name = pagenode.InnerText;
            string entId = pagenode.Attributes["data-entId"].Value;
            postdata = string.Format("id={0}&type={1}&name={2}&entId={3}", dataid, type, name, entId);
            pagedata = null;
            while (pagedata == null)
            {
                pagedata = Http.POST("http://gsxt.cqgs.gov.cn/search_ent", postdata, Encoding.UTF8);
            }
            doc.LoadHtml(pagedata);
            pagenode = doc.DocumentNode.SelectSingleNode("//*[@id='left']");
            type = pagenode.Attributes["data-type"].Value;

            postdata = string.Format("entId={0}&id={1}&type={2}", entId, dataid, type);
            pagedata = null;
            while (pagedata == null)
            {
                pagedata = Http.Get("http://gsxt.cqgs.gov.cn/search_getEnt.action?" + postdata, Encoding.UTF8);
            }
            Dictionary<string, object> JSON = J2D.JsonToDictionary(pagedata.Replace(")]}',", ""));
            Dictionary<string, object> baseInfo = (Dictionary<string, object>)JSON["base"];
            if (baseInfo.ContainsKey("revdate"))
            {
                EnterpriseInfo[0] = EnterpriseName;
                EnterpriseInfo[1] = "Error";
                EnterpriseInfo[2] = "吊销日期" + baseInfo["revdate"];
                return EnterpriseInfo;
            }
            EnterpriseInfo[0] = baseInfo["entname"].ToString();
            EnterpriseInfo[1] = baseInfo.ContainsKey("lerep") ? baseInfo["lerep"].ToString() : EnterpriseInfo[1];
            EnterpriseInfo[1] = baseInfo.ContainsKey("pril") ? baseInfo["pril"].ToString() : EnterpriseInfo[1];
            EnterpriseInfo[2] = "";
            EnterpriseInfo[3] = baseInfo.ContainsKey("dom") ? baseInfo["dom"].ToString() : EnterpriseInfo[3];
            EnterpriseInfo[3] = baseInfo.ContainsKey("oploc") ? baseInfo["oploc"].ToString() : EnterpriseInfo[3];
            EnterpriseInfo[4] = baseInfo.ContainsKey("estdate") ? baseInfo["estdate"].ToString() : EnterpriseInfo[4];
            EnterpriseInfo[4] = baseInfo.ContainsKey("regdate") ? baseInfo["regdate"].ToString() : EnterpriseInfo[4];
            EnterpriseInfo[5] = baseInfo.ContainsKey("regcap") ? baseInfo["regcap"].ToString() + " 万" : EnterpriseInfo[5];
            EnterpriseInfo[6] = EnterpriseInfo[1];
            EnterpriseInfo[7] = "";
            EnterpriseInfo[8] = "";
            EnterpriseInfo[9] = baseInfo["enttype"].ToString();

            EnterpriseInfo[10] = baseInfo.ContainsKey("opscope") ? baseInfo["opscope"].ToString() : EnterpriseInfo[10];
            EnterpriseInfo[10] = baseInfo.ContainsKey("opscoandform") ? baseInfo["opscoandform"].ToString() : EnterpriseInfo[10];
            EnterpriseInfo[10] = baseInfo.ContainsKey("opscotype") ? baseInfo["opscotype"].ToString() : EnterpriseInfo[10];
            EnterpriseInfo[7] = string.Format(
                "统一社会信用代码/注册号：{0} 名称：{1} 类型：{2} 法定代表人：{3} 注册资本：{4} 万 成立日期：{5} 住所：{6} 营业期限自：{7}至永久 经营范围：{8} 登记机关：{9} 核准日期：{10} 登记状态：{11} ",
                baseInfo["regno"].ToString(),
                EnterpriseInfo[0],
                EnterpriseInfo[9],
                EnterpriseInfo[1],
                EnterpriseInfo[5],
                EnterpriseInfo[4],
                EnterpriseInfo[3],
                baseInfo.ContainsKey("opfrom") ? baseInfo["opfrom"].ToString() : EnterpriseInfo[4],
                EnterpriseInfo[10],
                baseInfo["regorg"].ToString(),
                baseInfo["issblicdate"].ToString(),
                baseInfo["opstate"].ToString()
                );
            EnterpriseInfo[10] = "";

            String getdailyURL = @"http://gsxt.cqgs.gov.cn/search_getYearReport.action?";
            String getreportURL = @"http://gsxt.cqgs.gov.cn/search_getYearReportDetail.action?";
            String yearreportURL = "";
            String searchdaily = "";
            String yearnum = "";
            yearreportURL = getdailyURL + "id=" + dataid + "&type=" + type;
            searchdaily = Http.Get(yearreportURL, Encoding.UTF8);
            if (searchdaily.Contains("\"year\""))
            {
                yearnum = searchdaily.Substring(searchdaily.IndexOf("\"year\"") + 7, 4);
            }
            String yearreport = "";
            if (yearnum != "")
            {
                String getURL = getreportURL + "id=" + dataid + "&type=" + type + "&year=" + yearnum;
                yearreport = Http.Get(getURL, Encoding.UTF8);
                Dictionary<string, object> reportData = J2D.JsonToDictionary(yearreport);
                Dictionary<string, object> reportBase = (Dictionary<string, object>)reportData["base"];
                EnterpriseInfo[2] = reportBase.ContainsKey("tel") ? reportBase["tel"].ToString() : "无";
                EnterpriseInfo[8] = reportBase.ContainsKey("email") ? reportBase["email"].ToString() : "无";
            }
            return EnterpriseInfo;
        }
        /// <summary>
        /// 获取一组企业信息
        /// </summary>
        /// <param name="EnterpriseNames">企业名称组</param>
        /// <returns>企业信息组</returns>
        public static List<string[]> GetEnterpriseInfos(List<string> EnterpriseNames)
        {
            List<string[]> EnterpriseInfos = new List<string[]>();
            EnterpriseInfos.Clear();
            int EnterpriseNameCount = EnterpriseNames.Count;
            for (int i = 0; i < EnterpriseNameCount; i++)
            {
                labelInfoText = string.Format("正在获取数据..<{0}/{1}>", i + 1, EnterpriseNameCount);
                EnterpriseInfos.Add(GetEnterpriseInfo(EnterpriseNames[i]));
            }
            return EnterpriseInfos;
        }

        /// <summary>
        /// 保存企业数据到Excel文件
        /// </summary>
        /// <param name="EnterpriseInfos">企业数据组</param>
        public static void SaveEnterpriseInfos(List<string[]> EnterpriseInfos)
        {
            // 创建Excel文档
            Excel.Application ExcelApp = new Excel.Application();
            Excel.Workbook ExcelDoc = ExcelApp.Workbooks.Add(Type.Missing);
            Excel.Worksheet xlSheet = ExcelDoc.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            ExcelApp.DisplayAlerts = false;

            // 单元格下标是从[1，1]开始的
            Int32 Row = 1;
            Int32 Column = 1;
            xlSheet.Cells[Row, Column = 1] = "序号";
            xlSheet.Cells[Row, ++Column] = "企业名称";
            xlSheet.Cells[Row, ++Column] = "联系人";
            xlSheet.Cells[Row, ++Column] = "联系电话";
            xlSheet.Cells[Row, ++Column] = "公司地址";
            xlSheet.Cells[Row, ++Column] = "成立时间";
            xlSheet.Cells[Row, ++Column] = "注册资本";
            xlSheet.Cells[Row, ++Column] = "法人代表";
            xlSheet.Cells[Row, ++Column] = "公司信息";
            xlSheet.Cells[Row, ++Column] = "QQ/邮箱";
            xlSheet.Cells[Row, ++Column] = "公司性质";
            foreach (string[] EnterpriseInfo in EnterpriseInfos)
            {
                Row++;
                xlSheet.Cells[Row, Column = 1] = Row - 1;
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[0];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[1];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[2];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[3];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[4];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[5];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[6];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[7];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[8];
                xlSheet.Cells[Row, ++Column] = EnterpriseInfo[9];

                if (EnterpriseInfo[1] == "Error")
                {
                    Excel.Range ErrorRange = xlSheet.Rows[Row] as Excel.Range;
                    ErrorRange.Interior.Color = Color.FromArgb(244, 176, 132);
                }
            }

            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "保存数据";
            saveFile.Filter = "Excel文件|*.xlsx";
            Boolean FileIsUsed = true;
            while (FileIsUsed)
            {
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (File.Exists(saveFile.FileName))
                        {
                            File.Move(saveFile.FileName, saveFile.FileName);
                        }
                        FileIsUsed = false;
                    }
                    catch (Exception)
                    {
                        FileIsUsed = true;
                    }
                }
                else
                {
                    break;
                }
                if (FileIsUsed)
                {
                    if (MessageBox.Show("指定文件已被占用，请关闭后重试！", "Error", MessageBoxButtons.RetryCancel) == DialogResult.Cancel)
                    {
                        break;
                    }
                }
                if (FileIsUsed == false)
                {
                    // 文件保存
                    xlSheet.SaveAs(saveFile.FileName);
                    ExcelDoc.Close(Type.Missing, saveFile.FileName, Type.Missing);
                    ExcelApp.Quit();
                }
            }
        }

        private void Search_Click(object sender, EventArgs e)
        {
            Search.Enabled = false;
            labelInfoText = "正在获取数据...";
            EnterpriseNameList.Clear();
            foreach (string text in InformationBox.Lines)
            {
                if (text.Trim() == "") continue;
                EnterpriseNameList.Add(text);
            }
            if (EnterpriseNameList.Count == 1)
            {
                GetEnterpriseInfoOne.RunWorkerAsync();
            }
            else if (EnterpriseNameList.Count > 1)
            {
                GetEnterpriseInfoAll.RunWorkerAsync();
            }
            if (EnterpriseNameList.Count == 0)
            {
                InformationBox.Text = "正在获取小微企业名录...";
                GetEnterpriseNameList.RunWorkerAsync();
            }
        }

        private void Infotimer_Tick(object sender, EventArgs e)
        {
            if (labelInfoText == null)
            {
                labelInfo.Text = "在文本框填入公司名称（一行一个），然后点击查询按钮！";
            }
            else
            {
                labelInfo.Text = labelInfoText;
            }
        }

        private void SearchPlatform_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose(true);
            this.Close();
            Application.Exit();
        }

        private void GetEnterpriseInfoOne_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = GetEnterpriseInfo(EnterpriseNameList[0]);
        }

        private void GetEnterpriseInfoOne_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            InformationBox.Text = null;
            foreach (string data in (string[])e.Result)
            {
                InformationBox.Text += (data + "\t");
            }
            labelInfoText = null;
            Search.Enabled = true;
        }

        private void GetEnterpriseInfoAll_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = GetEnterpriseInfos(EnterpriseNameList);
        }

        private void GetEnterpriseInfoAll_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string[]> EnterpriseInfos = (List<string[]>)e.Result;
            SaveEnterpriseInfos(EnterpriseInfos);
            labelInfoText = null;
            Search.Enabled = true;
        }

        private void GetEnterpriseNameList_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = GetComNameList();
        }

        private void GetEnterpriseNameList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            EnterpriseNameList = (List<string>)e.Result;
            if (EnterpriseNameList.Count > 0)
            {
                GetEnterpriseInfoAll.RunWorkerAsync();
            }
        }
    }
}
